#include "HixlApi.h"
#include "HixlCsClient.h"

namespace hixl {
    hccl::HcclResult HixlCSClientCreate(char *server_ip,
                                        uint32_t server_port,
                                        const hccl::EndPoint *end_point,
                                        ClientHandle *client_handle) {
        if (server_ip == nullptr || end_point == nullptr) {
            return hccl::HcclResult::E_PARA;
        }

        try {
            auto *client = new(std::nothrow) HixlCsClient();
            if (client == nullptr) {
                return hccl::HcclResult::E_PARA;
            }

            hccl::HcclResult ret = client->Create(server_ip, server_port, end_point);
            if (ret != hccl::HcclResult::SUCCESS) {
                delete client;
                return ret;
            }

            *client_handle = static_cast<ClientHandle>(client);
            return hccl::HcclResult::SUCCESS;
        } catch (...) {
            return hccl::HcclResult::E_PARA;
        }
    }

    hccl::HcclResult HixlCSClientConnect(ClientHandle *client_handle) {
        if (client_handle == nullptr || *client_handle == nullptr) {
            return hccl::HcclResult::E_PARA;
        }

        auto *client = static_cast<HixlCsClient *>(*client_handle);
        return client->Connect();
    }

    hccl::HcclResult HixlCSClientGetStatus(ClientHandle client_handle,
                                           int32_t *status) {
        if (client_handle == nullptr || status == nullptr) {
            return hccl::HcclResult::E_PARA;
        }

        auto *client = static_cast<HixlCsClient *>(client_handle);
        return client->GetStatus(status);
    }

    hccl::HcclResult HixlCSClientGetRemoteMem(ClientHandle client_handle,
                                              hccl::HcclMem **remote_mem_list,
                                              char **mem_tag_list,
                                              uint32_t *list_num,
                                              uint32_t timeout) {
        if (client_handle == nullptr ||
            remote_mem_list == nullptr ||
            mem_tag_list == nullptr ||
            list_num == nullptr) {
            return hccl::HcclResult::E_PARA;
        }

        auto *client = static_cast<HixlCsClient *>(client_handle);
        return client->GetRemoteMem(remote_mem_list, mem_tag_list, list_num, timeout);
    }

    hccl::HcclResult HixlCSClientDestroy(ClientHandle client_handle) {
        if (client_handle == nullptr) {
            return hccl::HcclResult::E_PARA;
        }

        auto *client = static_cast<HixlCsClient *>(client_handle);
        hccl::HcclResult ret = client->Destroy();
        if (ret == hccl::HcclResult::SUCCESS) {
            delete client;
        }
        return ret;
    }
} // namespace hixl
